package com.m3839.sdk.common.event;

import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

/**
 * @author ChenBaoyang
 * @description: SubjectBus
 * @date 2021/11/13 11:21
 */
public class SubjectBus {

    private Map<String, RealSubject<Object>> subjectMap = new HashMap<>();

    private SubjectBus() {

    }

    private static class SingletonHolder {
        private static final SubjectBus DEFAULT_BUS = new SubjectBus();
    }

    public static SubjectBus get() {
        return SingletonHolder.DEFAULT_BUS;
    }


    /**
     * 抛事件
     * @param key 监听的key
     */
    public void postValue(String key){
        RealSubject<Object> subject = subjectMap.get(key);
        if(subject != null) {
            subject.makeChanged(null);
        }
    }

    /**
     * 抛事件
     * @param key 监听的key
     * @param o 数据
     */
    public void postValue(String key, Object o){
        RealSubject<Object> subject = subjectMap.get(key);
        if(subject != null) {
            subject.makeChanged(o);
        }
    }

    /**
     * 监听事件
     *
     * @param key 监听的key
     * @param observer 观察者
     */
    public void observe(String key, Observer observer) {
        if (!subjectMap.containsKey(key)) {
            subjectMap.put(key, new RealSubject<>());
        }
        subjectMap.get(key).addObserver(observer);
    }

    /**
     * 释放资源
     */
    public void release() {
        for (Map.Entry<String, RealSubject<Object>> entry : subjectMap.entrySet()) {
            entry.getValue().deleteObservers();
        }
        subjectMap.clear();
    }

    /**
     * 针对单一资源的key释放所有监听者
     * @param key 事件key
     */
    public void release(String key) {
        subjectMap.get(key).deleteObservers();
    }

    /**
     * 针对单一资源的释放指定监听者
     * @param key 事件key
     * @param observer 观察者
     */
    public void release(String key, Observer observer) {
        subjectMap.get(key).deleteObserver(observer);
    }

    public static class RealSubject<T> extends Observable {

        public void makeChanged(T data) {
            setChanged();
            notifyObservers(data);
        }
    }

    public static class RealObserver implements Observer {

        @Override
        public void update(Observable o, Object arg) {
            System.out.println("调用了-->"+arg);
        }
    }

    public static void main(String[] args) {
        RealSubject<Integer> subject = new RealSubject<Integer>();
        RealObserver observer = new RealObserver();
        subject.addObserver(observer);
        subject.makeChanged(111);
    }
}
